'use client';

import { PaginationState } from '../types/pokemon';

interface PaginationProps {
  pagination: PaginationState;
  onPageChange: (page: number) => void;
}

export default function Pagination({ pagination, onPageChange }: PaginationProps) {
  const { currentPage, itemsPerPage, totalItems } = pagination;
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  
  // 生成页码数组
  const getPageNumbers = (): number[] => {
    const pages: number[] = [];
    const maxPagesToShow = 5;
    
    if (totalPages <= maxPagesToShow) {
      // 如果总页数小于等于要显示的最大页数，显示所有页
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      // 否则，显示当前页附近的页码
      let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
      let endPage = startPage + maxPagesToShow - 1;
      
      if (endPage > totalPages) {
        endPage = totalPages;
        startPage = Math.max(1, endPage - maxPagesToShow + 1);
      }
      
      for (let i = startPage; i <= endPage; i++) {
        pages.push(i);
      }
      
      // 如果开始页不是第一页，添加省略号标识
      if (startPage > 1) {
        pages.unshift(-1); // 使用负数表示省略号
        pages.unshift(1);  // 始终显示第一页
      }
      
      // 如果结束页不是最后一页，添加省略号标识
      if (endPage < totalPages) {
        pages.push(-2); // 使用另一个负数表示省略号
        pages.push(totalPages); // 始终显示最后一页
      }
    }
    
    return pages;
  };
  
  // 生成页码按钮
  const renderPageButtons = () => {
    return getPageNumbers().map((pageNum, index) => {
      // 省略号
      if (pageNum < 0) {
        return (<span key={`ellipsis-${index}`} className="px-2 py-1">...</span>);
      }
      
      // 页码按钮
      return (
        <button
          key={pageNum}
          onClick={() => onPageChange(pageNum)}
          className={`px-3 py-1 rounded-md ${pageNum === currentPage ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800 hover:bg-gray-300'}`}
        >
          {pageNum}
        </button>
      );
    });
  };
  
  return (
    <div className="flex flex-col md:flex-row justify-center items-center mt-6 gap-4">
        <div className="flex items-center gap-2">
        <button
          onClick={() => onPageChange(currentPage - 1)}
          disabled={currentPage === 1}
          className={`px-3 py-1 rounded-md ${currentPage === 1 ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-gray-200'}`}
        >
          上一页
        </button>
        
        <div className="flex gap-1">
          {renderPageButtons()}
        </div>
        
        <button
          onClick={() => onPageChange(currentPage + 1)}
          disabled={currentPage === totalPages}
          className={`px-3 py-1 rounded-md ${currentPage === totalPages ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-gray-200'}`}
        >
          下一页
        </button>
      </div>
    </div>
  );
}
